package cn.edu.fzu.homemaking.dfa;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;

final class DfaNode {

    private final Character         value;
    private boolean                 end;

    private Map<Character, DfaNode> tree;

    DfaNode(char value, boolean end) {
        this.value = value;
        this.end = end;
    }


    /** 添加一片叶子 **/
    DfaNode addLeaf(DfaNode leaf) {

        if (tree == null) {
            tree = new HashMap<>();
        }

        DfaNode previousLeaf = tree.get(leaf.value);
        if (previousLeaf == null) {
            tree.put(leaf.value, leaf);
            return leaf;
        } else if (leaf.end && !previousLeaf.end) {
            previousLeaf.end = true;
        }
        return previousLeaf;
    }


    @Nullable
    DfaNode getLeaf(char key) {
        return tree == null ? null : tree.get(key);
    }


    boolean isEnd() {
        return end;
    }


    String draw(StringBuilder sb, String prefix) {

        sb.append('\n');
        if (StringUtils.isNotEmpty(prefix)) {
            int i = 0;
            for (char c : prefix.toCharArray()) {
                if (i >= prefix.length() - 2) {
                    sb.append(c);
                } else if (c == '─' || c == '└') {
                    sb.append(' ');
                } else {
                    sb.append('│');
                }
                i++;
            }
        }
        sb.append(value);
        if (end) {
            sb.append('.');
        }

        if (tree != null) {
            int i = 0;
            int length = tree.values().size();
            boolean last;
            for (DfaNode node : tree.values()) {
                last = i == length - 1;
                node.draw(sb, prefix + (last ? "└─" : "├─"));
                i++;
            }
        }

        return sb.toString();
    }

}
